package com.ujoku.payment.weChat.protocol.app_pay_protocol;

import com.ujoku.payment.weChat.common.Configure;
import com.labillusion.core.util.RandomStringGenerator;
import com.ujoku.payment.weChat.common.Signature;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by suggestion on 2015/4/9.
 */
public class AppPayProtocol {
    private String appid;
    private String key;
    private String partnerid;
    private String prepayid;
    private String noncestr;
    private String timestamp;

    private String sign;

    public AppPayProtocol(String prepayid){
        setAppid(Configure.getAppid());
        setKey(Configure.getKey());
        setPartnerid(Configure.getMchid());
        setPrepayid(prepayid);
        setTimestamp(String.valueOf(System.currentTimeMillis() / 1000 + 8 * 3600));
        setNoncestr(RandomStringGenerator.getRandomStringByLength(32));
        String sign = Signature.getSign(toMap(),"Sign=WXPay");
        setSign(sign);
    }


    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getAppid() {
        return appid;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public String getPartnerid() {
        return partnerid;
    }

    public void setPartnerid(String partnerid) {
        this.partnerid = partnerid;
    }

    public String getPrepayid() {
        return prepayid;
    }

    public void setPrepayid(String prepayid) {
        this.prepayid = prepayid;
    }

    public String getNoncestr() {
        return noncestr;
    }

    public void setNoncestr(String noncestr) {
        this.noncestr = noncestr;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public Map<String,Object> toMap(){
        Map<String,Object> map = new HashMap<String, Object>();
        Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            Object obj;
            try {
                obj = field.get(this);
                if(obj!=null){
                    map.put(field.getName(), obj);
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }
}
